/**
 * lisenses
 *
 */
package com.openjawtech.xscraper.flights.service.impl;

import com.openjawtech.xscraper.flights.SearchService;
import com.openjawtech.xscraper.schema.FlightsType;
import com.openjawtech.xscraper.schema.FlightType;
import com.openjawtech.xscraper.flights.dao.AirportDAO;
import com.openjawtech.xscraper.flights.dao.FlightDAO;
import com.openjawtech.xscraper.flights.dao.DAOFactory;
import com.openjawtech.xscraper.flights.domain.Airport;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.math.BigDecimal;
import java.util.List;
import java.util.Date;

/**
 * <p>implement all the method of search service
 *
 * <p>18/02/2009
 * @author Wenbo.Sun
 */
public class SearchServiceImpl implements SearchService {

    private static final Log log = LogFactory.getLog(SearchServiceImpl.class);
    private AirportDAO airportDAO;
    private FlightDAO flightDAO;

    public SearchServiceImpl() {
        airportDAO = DAOFactory.createAirportDAO();
        flightDAO = DAOFactory.createFlightDAO();
    }

    @Override
    public List<String> getAllAirports() {
        return airportDAO.getAllNames();
    }

    @Override
    public List<String> getAllArrivals(String departure) {
        return airportDAO.getArrivals(departure);
    }

    @Override
    public FlightsType search(FlightsType flights) {
        log.debug("start to search flight information");
        String departureName = flights.getDeparture();
        String arrivalName = flights.getArrival();
        if (departureName == null || arrivalName == null || "".equals(departureName) || "".equals(arrivalName)) {
            log.error("departure or/and arrival name is/are invalid");
            return null;
        }
        departureName = departureName.toLowerCase().trim();
        arrivalName = arrivalName.toLowerCase().trim();
        if (airportDAO.isExisted(departureName) && airportDAO.isExisted(arrivalName)) {
            Airport departure = airportDAO.getByName(departureName);
            Airport arrival = airportDAO.getByName(arrivalName);
            if (!flightDAO.isExisted(departure, arrival)) {
                return null;
            }
            for (FlightType flightType : flights.getFlightArray()) {
                Date travelDate;
                if (flightType.getTravelDate() != null) {
                    travelDate = flightType.getTravelDate().getTime();
                    if (flightDAO.isExisted(departure, arrival, travelDate)) {
                        double price = flightDAO.getByTravel(departure, arrival, travelDate).getPrice();
                        flightType.setPrice(BigDecimal.valueOf(price));
                    }
                }
            }
            log.debug("searching complete");
            return flights;
        }
        return null;

    }

    @Override
    public boolean checkAirportName(String name) {
        return airportDAO.isExisted(name);
    }
}
